package com.xjscrm.console.service.customer.list.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.group.MicaTriggerGroupKickMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.DeviceTypeEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.group.WwGroupQuery;
import com.xjscrm.console.param.list.BatchDeleListDto;
import com.xjscrm.console.param.list.BlackWhiteListLogQuery;
import com.xjscrm.console.param.list.WwCustomerBlackDto;
import com.xjscrm.console.param.list.WwCustomerListQuery;
import com.xjscrm.console.param.user.ChildMerchatDto;
import com.xjscrm.console.param.wwDevice.WwDeviceQuery;
import com.xjscrm.console.service.common.user.UserService;
import com.xjscrm.console.service.customer.childUser.ChildMerchatService;
import com.xjscrm.console.service.customer.list.BlackListService;
import com.xjscrm.console.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class BlackListServiceImpl implements BlackListService {

    @Autowired
    private BlackListMapper blackListMapper;

    @Autowired
    private WwCustomerMapper wwCustomerMapper;

    @Autowired
    private WwCustomerBlackwhitelistLogMapper wwCustomerBlackwhitelistLogMapper;

    @Autowired
    private ChildMerchatService childMerchatService;

    @Autowired
    private UserService userService;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private WwGroupMapper wwGroupMapper;

    @Autowired
    private WwGroupMemberMapper wwGroupMemberMapper;

    @Autowired
    private SendMsgProducer sendMsgProducer;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBlackList(WwCustomerBlackDto wwCustomerBlackDto) {
        if(wwCustomerBlackDto.getMerId()==null){
        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(wwCustomerBlackDto.getWxid()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "微信ID为空");
        }
        if(wwCustomerBlackDto.getOperatorType()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }
        //主账号
        if(wwCustomerBlackDto.getOperatorType()==0){
            wwCustomerBlackDto.setOperatorId(wwCustomerBlackDto.getMerId());
        }
        //子账号
        if(wwCustomerBlackDto.getOperatorType()==1){
            wwCustomerBlackDto.setOperatorId(wwCustomerBlackDto.getChildId());
        }
        WwCustomerBlacklist wwCustomerBlacklist = new WwCustomerBlacklist();
        BeanUtil.copyProperties(wwCustomerBlackDto,wwCustomerBlacklist);

        WwCustomer wwCustomer= wwCustomerMapper.getByWxId(wwCustomerBlacklist.getWxid(),wwCustomerBlacklist.getMerId());
        if(wwCustomer==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "未找到该客户");
        }
        //添加黑名单
        wwCustomerBlacklist.setName(wwCustomer.getName());
        wwCustomerBlacklist.setHeadImg(wwCustomer.getHeadImgUrl());
        blackListMapper.addBlackList(wwCustomerBlacklist);

        //添加日志
        WwCustomerBlackwhitelistLog wwCustomerBlackwhitelistLog=new WwCustomerBlackwhitelistLog();
        BeanUtil.copyProperties(wwCustomerBlacklist,wwCustomerBlackwhitelistLog);
        wwCustomerBlackwhitelistLog.setType(0);
        wwCustomerBlackwhitelistLog.setOpt(0);
        wwCustomerBlackwhitelistLogMapper.addWwCustomerBlackwhitelistLog(wwCustomerBlackwhitelistLog);

        //踢出客户群
        kickOutGroupMember(wwCustomerBlacklist);
    }

    public void kickOutGroupMember(WwCustomerBlacklist wwCustomerBlacklist) {

        //获取商户的机器人
        WwDeviceQuery wwDeviceQuery=new WwDeviceQuery();
        wwDeviceQuery.setMerId(wwCustomerBlacklist.getMerId());
        List<WwDeviceVo> wwDeviceVoList = wwDeviceMapper.getWwDeviceList(wwDeviceQuery);
        if(wwDeviceVoList!=null&&!wwDeviceVoList.isEmpty()){
            for (WwDeviceVo wwDeviceVo:wwDeviceVoList) {
                //查询群主所在的群
                WwGroupQuery wwGroupQuery=new WwGroupQuery();
                wwGroupQuery.setMerId(wwCustomerBlacklist.getMerId());
                wwGroupQuery.setCreateWxid(wwDeviceVo.getDeviceId());
                List<WwGroupVo> wwGroupList = wwGroupMapper.getWwGroupList(wwGroupQuery);

                //查询群管理员所在的群
                WwGroupQuery query=new WwGroupQuery();
                query.setMerId(wwCustomerBlacklist.getMerId());
                query.setAdminWxid(wwDeviceVo.getDeviceId());
                List<WwGroupVo> wwGroupVoList = wwGroupMapper.getWwGroupList(query);

                //获取群微信ID集合
                Set<String> groupWxids = Stream.concat(wwGroupList.stream(), wwGroupVoList.stream()).map(WwGroupVo::getGroupWxid).collect(Collectors.toSet());

                if(!groupWxids.isEmpty()){

                    for (String groupWxid:groupWxids) {

                        WwGroupMember wwGroupMember = wwGroupMemberMapper.getByGroupWxIdAndWxid(groupWxid, wwCustomerBlacklist.getWxid(), wwCustomerBlacklist.getMerId());

                        if(wwGroupMember!=null){

                            wwGroupMemberMapper.deleById(wwGroupMember.getId(), wwGroupMember.getMerId());


                            //发送删除群成员指令
                            MicaTriggerGroupKickMsg micaTriggerGroupKickMsg = new MicaTriggerGroupKickMsg();
                            micaTriggerGroupKickMsg.setMessageId(wwGroupMember.getId());
                            micaTriggerGroupKickMsg.setGroupId(wwGroupMember.getGroupWxid());
                            micaTriggerGroupKickMsg.setWxIds(wwGroupMember.getWxid());

                            MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerGroupKickMsg, MicaTriggerType.TRIGGER_GROUP_KICK);
                            micaTriggerDto.setMerId(wwDeviceVo.getMerId());
                            micaTriggerDto.setDeviceId(wwDeviceVo.getDeviceId());
                            micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
                            sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
                        }
                    }
                }
            }
        }
    }


    @Override
    public Object getBlackList(WwCustomerListQuery wwCustomerBlackQuery) {
        if(wwCustomerBlackQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        String orderBy = OrderByUtil.getOrderBy(wwCustomerBlackQuery.getOrderByField(), wwCustomerBlackQuery.isAsc());
        PageHelper.startPage(wwCustomerBlackQuery.getCurrent(),wwCustomerBlackQuery.getSize(),orderBy);
        List<WwCustomerBlackVo> wwCustomerBlackVoList=blackListMapper.getBlackList(wwCustomerBlackQuery);
        if(wwCustomerBlackVoList==null){
            return new MyPageInfo<>(null);
        }
        for (WwCustomerBlackVo wwCustomerBlackVo:wwCustomerBlackVoList) {
            try {
                if(wwCustomerBlackVo.getOperatorType()==0){
                    BaseDto baseDto=new BaseDto();
                    baseDto.setMerId(wwCustomerBlackVo.getOperatorId());
                    Merchant merchant = userService.getById(baseDto);
                    wwCustomerBlackVo.setOperatorName(merchant.getUserAccount());
                }

                if(wwCustomerBlackVo.getOperatorType()==1){
                    ChildMerchatDto childMerchatDto=new ChildMerchatDto();
                    childMerchatDto.setMerId(wwCustomerBlackVo.getMerId());
                    childMerchatDto.setId(wwCustomerBlackVo.getOperatorId());
                    MerchatChild merchatChild = childMerchatService.getById(childMerchatDto);
                    wwCustomerBlackVo.setOperatorName(merchatChild.getUserAccount());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        MyPageInfo<WwCustomerBlackVo> pageInfo = new MyPageInfo<>(wwCustomerBlackVoList);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleBlackList(BatchDeleListDto batchDeleListDto) {
        if(batchDeleListDto.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if(batchDeleListDto.getId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        WwCustomerBlacklist wwCustomerBlacklist=blackListMapper.getById(batchDeleListDto.getId(),batchDeleListDto.getMerId());

        if(wwCustomerBlacklist==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该黑名单不存在");
        }

        //添加日志
        WwCustomerBlackwhitelistLog wwCustomerBlackwhitelistLog=new WwCustomerBlackwhitelistLog();
        BeanUtil.copyProperties(wwCustomerBlacklist,wwCustomerBlackwhitelistLog);
        wwCustomerBlackwhitelistLog.setType(0);
        wwCustomerBlackwhitelistLog.setOpt(1);
        wwCustomerBlackwhitelistLogMapper.addWwCustomerBlackwhitelistLog(wwCustomerBlackwhitelistLog);

        //删除黑名单
        blackListMapper.deleById(batchDeleListDto.getId(),batchDeleListDto.getMerId());



    }


    @Override
    public Object getBlackWhiteListLogList(BlackWhiteListLogQuery blackWhiteListLogQuery) {
        if(blackWhiteListLogQuery.getMerId()==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        String orderBy = OrderByUtil.getOrderBy(blackWhiteListLogQuery.getOrderByField(), blackWhiteListLogQuery.isAsc());
        PageHelper.startPage(blackWhiteListLogQuery.getCurrent(),blackWhiteListLogQuery.getSize(),orderBy);
        List<BlackWhiteListLogVo> blackWhiteListLogVoList=wwCustomerBlackwhitelistLogMapper.getBlackWhiteListLogList(blackWhiteListLogQuery);
        if(blackWhiteListLogVoList==null){
            return new MyPageInfo<>(null);
        }

        return new MyPageInfo<>(blackWhiteListLogVoList);
    }
}
